#include "../collections.h"

#include <stdlib.h>

queue queue_create()
{
	queue self = malloc(sizeof(struct queue));
	self->front = NULL;
	self->back = NULL;
	return self;
}

void queue_delete(queue self)
{
	queue_clear(self);
	free(self);
	self = NULL;
}

void queue_clear(queue self)
{
	node aux = self->front;
	while (aux != NULL)
	{
		node toremove = aux;
		aux = node_getlink(aux);
		node_delete(toremove);
	}
	self->back = NULL;
	self->front = NULL;
}

void _queue_enqueue(queue self, int T, void * value)
{
	node newnode = node_create(T, value, NULL);
	if (self->back != NULL)
		node_connect(self->back, newnode);

	self->back = newnode;

	if (self->front == NULL)
		self->front = newnode;
}

int _queue_dequeue(queue self, int T, void * value)
{
	if (queue_isempty(self))
		return 0;

	_queue_peek(self, T, value);
	node todelete = self->front;
	self->front = node_getlink(self->front);
	if (self->front == NULL)
		self->back = NULL;
	node_delete(todelete);

	return 1;
}

void _queue_peek(queue self, int T, void * value)
{
	node_read(self->front, T, value);
}

int queue_isempty(queue self)
{
	return self->front == NULL;
}

